<template>
  <div class="topology-toolbar-box">
    <div class="no-click-box" v-if="lockCanvas"></div>
    <el-tooltip :content="$t('message.tooltips.revoke')" effect="light">
      <div class="toolbar-item" @click="canvasUndo" :class="[!haveUndo&&'toolbar-no-click']">
        <svg class="toolbar-icon">
          <use v-bind:xlink:href="`#${haveUndo?'keowledge-a-zu4954':'keowledge-chexiao'}`"></use>
        </svg>
      </div>
    </el-tooltip>
    <el-tooltip :content="$t('message.tooltips.redo')" effect="light">
      <div class="toolbar-item" @click="canvasRedo"  :class="[!haveRedo&&'toolbar-no-click']">
        <svg class="toolbar-icon">
          <use v-bind:xlink:href="`#${haveRedo?'keowledge-huifu1':'keowledge-a-zu4956'}`"></use>
        </svg>
      </div>
    </el-tooltip>
    <div class="line"></div>
    <el-tooltip :content="`${isLock?$t('message.tooltips.unlock'):$t('message.tooltips.lock')}`" effect="light">
      <div class="toolbar-item" :class="[isLock && 'toolbar-item-active']"  @click="changeLock">
        <i class="toolbar-icon-i knowledge-iconfont" :class="[isLock?'keowledge-jiesuo':'keowledge-a-zu49191']"></i>
      </div>
    </el-tooltip>
    <el-tooltip :content="$t('message.tooltips.emptyCanvas')" effect="light">
      <div class="toolbar-item" @click="clearCanvas">
        <svg class="toolbar-icon">
          <use xlink:href="#keowledge-a-zu49531"></use>
        </svg>
      </div>
    </el-tooltip>
    <el-tooltip :content="$t('message.tooltips.paintingBrush')" effect="light">
      <div class="toolbar-item" :class="[isDrawLine && 'toolbar-item-active']"  @click="changeDrawLine">
        <i class="toolbar-icon-i knowledge-iconfont keowledge-huabi"></i>
      </div>
    </el-tooltip>
    <div class="line"></div>

    <div class="toolbar-item" ref="linkStyleRef" @click="openPop('linkStyle')">
      <svg class="toolbar-icon">
        <use v-bind:xlink:href="`#${lineName}`"></use>
      </svg>
      <span class="tool-name">{{$t('message.tooltips.connectionType')}}</span>
      <svg class="arrow-icon">
        <use xlink:href="#keowledge-a-zu4049"></use>
      </svg>
    </div>
    <div class="toolbar-item" ref="startStyleRef" @click="openPop('start')">
      <i class="toolbar-icon-i knowledge-iconfont" :class="[fromArrow]"></i>
      <span class="tool-name">{{$t('message.tooltips.startPoint')}}</span>
      <svg class="arrow-icon">
        <use xlink:href="#keowledge-a-zu4049"></use>
      </svg>
    </div>

    <div class="toolbar-item" ref="endStyleRef" @click="openPop('end')">
      <i class="toolbar-icon-i knowledge-iconfont" :class="[toArrow]"></i>
      <span class="tool-name">{{$t('message.tooltips.endPoint')}}</span>
      <svg class="arrow-icon">
        <use xlink:href="#keowledge-a-zu4049"></use>
      </svg>
    </div>

    <div class="line"></div>
    <el-tooltip :content="$t('message.tooltips.view100')" effect="light">
      <div class="toolbar-item" @click="onScaleDefault"> 
        <svg class="toolbar-icon">
          <use xlink:href="#keowledge-a-zu7777"></use>
        </svg>
      </div>
    </el-tooltip>
    <el-tooltip :content="$t('message.tooltips.windowView')" effect="light">
      <div class="toolbar-item" @click="onScaleWindow">
        <svg class="toolbar-icon">
          <use xlink:href="#keowledge-a-zu7776"></use>
        </svg>
      </div>
    </el-tooltip>
    <div class="scale-item">
      <el-icon @click="scaleChange('down')"><Minus /></el-icon>
      <span class="scale-text">{{scale}}%</span>
      <el-icon @click="scaleChange('up')"><Plus /></el-icon>
    </div>
    <el-popover
      ref="popoverRef"
      :virtual-ref="buttonRef"
      trigger="click"
      virtual-triggering
      :visible="popVisible"
      popper-class="topology-canvas-popover"
    >
      <div class="popover-box" v-click-outside="clickOutFun">
          <div v-for="(item,index) in popList" :key="index" class="pop-item" :class="[item.value==currentActive && 'pop-item-active',currentOpenPop!='linkStyle'&&'pop-center']"
            @click="changeStyle(item)">
            <!-- <svg class="pop-icon">
              <use v-bind:xlink:href="`${item.icon}`"></use>
            </svg> -->
            <i class="pop-icon knowledge-iconfont" :class="item.icon"></i>
            <span class="pop-name" v-if="currentOpenPop=='linkStyle'">{{item.name}}</span>
          </div>
      </div>
    </el-popover>
  </div>
</template>

<script setup lang="ts">
import {
  ref,
  reactive,
  toRefs,
  watch ,
  nextTick,
  onMounted,
  getCurrentInstance,
  computed
} from 'vue' 
import { useRouter } from "vue-router"
import { ClickOutside as vClickOutside } from 'element-plus'
import { Pen, PenType, deepClone } from '@meta2d/core';
import { useHookI18n } from '@/hooks/i18n'
const { locale,$t } = useHookI18n()
const router = useRouter();
const emit = defineEmits(["update:canvasScale"])
const props = defineProps({
  canvasScale:{
    type:Number,
    default:1
  },
  lockCanvas:{
    type:Boolean,
    default:false
  }
})
const linkStyleRef = ref()
const startStyleRef = ref()
const endStyleRef = ref()
const buttonRef = ref()
const popoverRef = ref()
const redoNum = ref(0)
const undoNum = ref(0)
const linkStyle = ref("curve")
const startIcon = ref('')
const endIcon = ref('')
const scale = ref(1)
const linkList = [
  { name: $t('message.typeMenu.curve'), icon: 'keowledge-a-zu7085', value: 'curve' },
  { name: $t('message.typeMenu.polyline'), icon: 'keowledge-zhexian', value: 'polyline' },
  { name: $t('message.typeMenu.line'), icon: 'keowledge-zhixian', value: 'line' },
  { name: $t('message.typeMenu.mind'), icon: 'keowledge-quxian', value: 'mind' }
]
const startAndEnd = [
  { name: 'line', icon: 'keowledge-a-zu7812', value: '' },
  { name: 'triangle', icon: 'keowledge-a-huaban14', value: 'triangle' },
  { name: 'diamond', icon: 'keowledge-a-huaban15', value: 'diamond' },
  { name: 'circle', icon: 'keowledge-a-zu7807', value: 'circle' },
  { name: 'lineDown', icon: 'keowledge-a-zu7814', value: 'lineDown' },
  { name: 'lineUp', icon: 'keowledge-a-zu7813', value: 'lineUp' },
  { name: 'triangleSolid', icon: 'keowledge-a-zu7806', value: 'triangleSolid' },
  { name: 'diamondSolid', icon: 'keowledge-a-zu7810', value: 'diamondSolid' },
  { name: 'circleSolid', icon: 'keowledge-a-zu7817', value: 'circleSolid' },
  { name: 'toLine', icon: 'keowledge-a-zu7815', value: 'line' },
]
const popVisible = ref(false)
const currentActive = ref('')
const currentOpenPop = ref('')
const popList = ref<Object[]>()
const lineName = computed(()=>{
  let val = 'keowledge-a-zu7085'
  linkList.forEach((item)=>{
    if(item.value==linkStyle.value) val=item.icon
  })
  return val
})
const fromArrow = computed(()=>{
  let val = 'keowledge-a-zu7812'
  startAndEnd.forEach((item)=>{
    if(item.value==startIcon.value) val=item.icon
  })
  return val
})
const toArrow = computed(()=>{
  let val = 'keowledge-a-zu7812'
  startAndEnd.forEach((item)=>{
    if(item.value==endIcon.value) val=item.icon
  })
  return val
})
const isLock = ref(false)
const isDrawLine = ref(false)
onMounted(()=>{
  scaleSubscriber(props.canvasScale);
})
const haveRedo = computed(()=>{
  return redoNum.value>0
})
const haveUndo =  computed(()=>{
  return undoNum.value>0
})
watch(()=>props.canvasScale,(newV)=>{
  scaleSubscriber(newV)
},{deep:true})
const scaleSubscriber = (val: number) => {
  scale.value = Math.round(val * 100);
};
function startOn(){
  isLock.value = meta2d.store.data.locked==1
  meta2d.on('update',()=>{
    undoNum.value+=1
  })
  meta2d.on('undo',()=>{
    undoNum.value-=1
    if(undoNum.value<=0){
      undoNum.value=0
    }
    redoNum.value+=1
  })
  meta2d.on('redo',()=>{
    redoNum.value-=1
    if(redoNum.value<=0){
      redoNum.value=0
    }
    undoNum.value+=1
  })
}
function openPop(type){
  currentOpenPop.value = type
  switch (type) {
    case 'linkStyle':
      buttonRef.value = linkStyleRef.value
      popList.value = linkList
      currentActive.value = linkStyle.value
      break;
    case 'start':
      buttonRef.value = startStyleRef.value
      popList.value = startAndEnd
      currentActive.value = startIcon.value
      break;
    case 'end':
      buttonRef.value = endStyleRef.value
      popList.value = startAndEnd
      currentActive.value = endIcon.value
      break;
    default:
      break;
  }
  popVisible.value = true
}
function changeStyle(item){
  currentActive.value = item.value
  switch (currentOpenPop.value) {
    case 'linkStyle':
      linkStyle.value = item.value
      if (meta2d) {
        meta2d.store.options.drawingLineName = item.value;
        meta2d.canvas.drawingLineName && (meta2d.canvas.drawingLineName = item.value);
        meta2d.store.active?.forEach((pen) => {
          meta2d.updateLineType(pen, item.value);
        });
      }
      break;
    case 'start':
      startIcon.value = item.value
      // 画布默认值
      meta2d.store.data.fromArrow = item.value;
      // 活动层的箭头都变化
      if (meta2d.store.active) {
        meta2d.store.active.forEach((pen: Pen) => {
          if (pen.type === PenType.Line) {
            pen.fromArrow = item.value;
            meta2d.setValue(
              {
                id: pen.id,
                fromArrow: pen.fromArrow,
              },
              {
                render: false,
              }
            );
          }
        });
        meta2d.render();
      }
      break;
    case 'end':
      endIcon.value = item.value
      // 画布默认值
      meta2d.store.data.toArrow = item.value;
      // 活动层的箭头都变化
      if (meta2d.store.active) {
        meta2d.store.active.forEach((pen: Pen) => {
          if (pen.type === PenType.Line) {
            pen.toArrow = item.value;
            meta2d.setValue(
              {
                id: pen.id,
                toArrow: pen.toArrow,
              },
              {
                render: false,
              }
            );
          }
        });
        meta2d.render();
      }
      break;
    default:
      break;
  }
  clickOutFun()
}
function clickOutFun(){
  popVisible.value = false
}
function onScaleDefault(){
  meta2d.scale(1);
  meta2d.centerView();
}
const onScaleWindow = () => {
  meta2d.fitView();
}
function scaleChange(val){
  switch (val) {
    case 'down':
      if(props.canvasScale-0.1>0.2){
        emit("update:canvasScale",props.canvasScale-0.1)
      }
      break;
    case 'up':
      emit("update:canvasScale",props.canvasScale+0.1)
      break
    default:
      break;
  }
  meta2d.scale()
}
function changeLock(){
  if(!isLock.value){
    meta2d.store.data.locked = 1
    isLock.value = true
  }else{
    meta2d.store.data.locked = 0
    isLock.value = false
  }
}
function canvasUndo(){
  if(!haveUndo.value) return
  meta2d.undo()
}
function canvasRedo(){
  if(!haveRedo.value) return
  meta2d.redo()
}
function clearCanvas(){
  meta2d.delete(meta2d.data().pens)
}
function changeDrawLine(){
  if (isDrawLine.value) {
    isDrawLine.value = false;
    meta2d.finishDrawLine();
    meta2d.drawLine();
    meta2d.store.options.disableAnchor = true;
  } else {
    isDrawLine.value = true;
    meta2d.drawLine(meta2d.store.options.drawingLineName);
    meta2d.store.options.disableAnchor = false;
  }
}
defineExpose({
  startOn,
  changeLock
})
</script>
<style lang="scss" scoped>
.topology-toolbar-box{
  min-height: 40px;
  border-bottom: 1px solid #eeeff0;
  background-color: #fff;
  padding: 0px 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  user-select: none;
  position: relative;
  .no-click-box{
    position: absolute;
    cursor: no-drop;
    width: 100%;
    height: 100%;
    top: 0px;
    left: 0px;
    z-index: 9;
  }
  .line{
    width: 1px;
    height: 16px;
    background-color: #f5f6f7;
    margin: 0px 8px;
  }
  .scale-item{
    padding: 4px;
    height: 24px;
    margin: 0px 4px;
    display: flex;
    align-items: center;
    justify-content: center;
    .scale-text{
      font-size: 12px;
      color: #363B4C;
      margin: 0px 4px;
      width: 30px;
      text-align: center;
    }
    .el-icon{
      width: 24px;
      height: 24px;
      font-size: 16px;
      cursor: pointer;
      padding: 4px;
      border-radius: 4px;
      &:hover{
        background: #F5F6F7;
      }
    }
  }
  .toolbar-item{
    margin: 0px 4px;
    min-width: 24px;
    height: 24px;
    border-radius: 4px;
    padding: 4px;
    cursor: pointer;
    display: flex;
    align-items: center;
    justify-content: center;
    .tool-name{
      padding: 0px 8px;
      font-size: 12px;
      color: #363B4C;
    }
    .toolbar-icon{
      width: 16px;
      height: 16px;
    }
    .toolbar-icon-i{
      font-size: 16px;
    }
    .arrow-icon{
      width: 16px;
      height: 16px;
    }
    &:hover{
      background: #F5F6F7;
    }
  }
  .toolbar-item-active{
    color: #fff !important;
    background: #1E6FFF !important;
  }
  .toolbar-no-click{
    // cursor: no-drop;
  }
}
</style>
<style lang="scss">
.topology-canvas-popover{
  min-width: 100px !important;
  width: auto !important;
  padding: 0px !important;
  .popover-box{
    margin: 0 4px;
    .pop-item{
      display: flex;
      align-items: center;
      // justify-content: center;
      height: 32px;
      margin: 4px 0;
      cursor: pointer;
      border-radius: 4px 4px 4px 4px;
      padding: 0px 4px;
      .pop-icon{
        font-size: 16px;
        // width: 16px;
        // height: 16px;
        margin-right: 8px;
      }
      .pop-name{
        font-size: 14px;
        color: #363B4C;
      }
      &:hover{
        background: #F5F6F7;
      }
    }
    .pop-center{
      justify-content: center;
    }
    .pop-item-active{
      background-color: #DDEAFF !important;
      .pop-icon{
        color: #1E6FFF !important;
      }
      .pop-name{
        color: #1E6FFF !important;
      }
    }
  }
}
</style>
